(function() {
	"use strict";

	var DEFAULT_ROUTE = 'one';
	var template = document.querySelector('template[is="auto-binding"]');
	var ajax, pages, scaffold;
	var cache = {};

	template.pages = [
	                  {name: 'Shadow DOM 101', hash: 'one', url: 'http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom/'},
	                  {name: 'Shadow DOM 201', hash: 'two', url: 'http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-201/'},
	                  {name: 'Shadow DOM 301', hash: 'three', url: 'http://www.html5rocks.com/en/tutorials/webcomponents/shadowdom-301/'},
	                  {name: 'Custom Elements', hash: 'four', url: 'http://www.html5rocks.com/en/tutorials/webcomponents/customelements/'}
	                  ];

	template.addEventListener('template-bound', function(e) {
		scaffold = document.querySelector('#scaffold');
		ajax = document.querySelector('#ajax');
		pages = document.querySelector('#pages');

		this.route = this.route || DEFAULT_ROUTE; // Select initial route.
	});

	template.menuItemSelected = function(e, detail, sender) {
		if (detail.isSelected) {
			// Need to wait one rAF so <core-ajax> has it's URL set.
			this.async(function() {
				if (!cache[ajax.url]) {
					ajax.go();
				}
				scaffold.closeDrawer();
			});
		}
	};

	template.cyclePages = function(e, detail, sender) {
		// If click was on a link, navigate and don't cycle page.
		if (e.path[0].localName == 'a') {
			return;
		}
		e.shiftKey ? sender.selectPrevious(true) : sender.selectNext(true);
	};


	template.ajaxLoad = function(e, detail, sender) {
		e.preventDefault();
	};

	template.onResponse = function(e, detail, sender) {
		var article = detail.response.querySelector('#article-content');

		article.querySelector('.byline').remove();

		// Fix up image paths to not be local.
//		[].forEach.call(article.querySelectorAll('img'), function(img) {
//			img.setAttribute('src', img.src);
//		});

		var html = article.innerHTML;

		cache[ajax.url] = html; // Primitive caching by URL.

		this.injectBoundHTML(html, pages.selectedItem.firstElementChild);
	};

})();